package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtil;
import com.itheima.utils.Md5Util;
import com.itheima.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /* 注册接口 */
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        //首先进行注册账号的查询，不存在才进行注册，否则注册失败
        User u = userService.findByUsername(username);
        if (u == null) {
            userService.register(username, password);
            return Result.success();
        } else {
            return Result.error("该账号已存在！");
        }
    }

    /* 登陆接口 */
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        User u = userService.findByUsername(username);
        if (u == null) {
            return Result.error("账号输入错误！");
        } else {
            String md5Password = Md5Util.getMD5String(password);
            if (!md5Password.equals(u.getPassword())) {
                return Result.error("密码输入错误！");
            }
        }
        //在成功登陆后进行jwt令牌的生成即开始做登陆验证
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", u.getId());
        claims.put("username", u.getUsername());
        String token = JwtUtil.genToken(claims);
        //将该令牌拷贝一份放置于redis中用于优化登陆验证
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set(token, token, 1, TimeUnit.DAYS);
        return Result.success(token);
    }

    /* 获取用户详细信息接口 */
    @GetMapping("/userInfo")
    public Result<User> userInfo() {
//        从暂存器中拿到用户账号名之后进行查找用户信息后返回
        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User user = userService.findByUsername(username);
        return Result.success(user);
    }

    /* 更新用户信息接口 */
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        userService.update(user);
        return Result.success();
    }

    /* 更新用户头像接口 */
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userService.updateAvatar(avatarUrl, id);
        return Result.success();
    }

    /* 更改用户密码 */
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params, @RequestHeader("Authorization") String token) {
        //首先先做参数得校验
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        for (String pwd : params.values()) {
            if (!StringUtils.hasLength(pwd)) {
                return Result.error("参数不符合标准！！！");
            }
        }

        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        Integer id = (Integer) claims.get("id");
        User user = userService.findByUsername(username);
        if (!user.getPassword().equals(Md5Util.getMD5String(oldPwd))) {
            return Result.error("旧密码输入错误！！!");
        }

        if (!newPwd.equals(rePwd)) {
            return Result.error("两次输出得新密码不一致！！!");
        }
        //然后进行更改密码操作和返回结果
        userService.updatePwd(newPwd, id);
        //在成功修改密码后将redis中的令牌删去
        stringRedisTemplate.opsForValue().getOperations().delete(token);
        return Result.success();
    }
}
